#!/usr/bin/env bash
# Summary: Display prefix for a Ruby version
# Usage: rbenv prefix [<version>]
#
# Displays the directory where a Ruby version is installed. If no
# version is given, `rbenv prefix' displays the location of the
# currently selected version.

set -e
[ -n "$RBENV_DEBUG" ] && set -x

# Provide rbenv completions
if [ "$1" = "--complete" ]; then
  echo system
  exec rbenv-versions --bare
fi

if [ -n "$1" ]; then
  export RBENV_VERSION="$1"
elif [ -z "$RBENV_VERSION" ]; then
  RBENV_VERSION="$(rbenv-version-name)"
fi

if [ "$RBENV_VERSION" = "system" ]; then
  if RUBY_PATH="$(rbenv-which ruby)"; then
    RUBY_PATH="${RUBY_PATH%/*}"
    RBENV_PREFIX_PATH="${RUBY_PATH%/bin}"
    echo "${RBENV_PREFIX_PATH:-/}"
    exit
  else
    echo "rbenv: system version not found in PATH" >&2
    exit 1
  fi
fi

RBENV_PREFIX_PATH="${RBENV_ROOT}/versions/${RBENV_VERSION}"
if [ ! -d "$RBENV_PREFIX_PATH" ]; then
  echo "rbenv: version \`${RBENV_VERSION}' not installed" >&2
  exit 1
fi

echo "$RBENV_PREFIX_PATH"
